<template>
    <el-dialog
      v-model="visible"
      :title="$t('添加钱包地址')"
      :width="isMobile ? '90%' : '520px'"
      :close-on-click-modal="false"
      class="wallet-dialog"
      destroy-on-close
    >
      <div class="dialog-content">
        <!-- 安全提示 -->
        <div class="security-tip">
          <i class="fas fa-shield-alt"></i>
          <span>{{ $t('请仔细核对钱包地址，错误的地址可能导致资产丢失') }}</span>
        </div>

        <!-- 表单内容 -->
        <div class="form-content">
          <!-- 币种 -->
          <div class="form-item">
            <div class="label">{{ $t('币种') }}</div>
            <div class="crypto-card" :class="{'iscrypto-card':cenryindex == 'USDT' }" @click="TaBa('USDT')">
              <img src="https://cryptologos.cc/logos/tether-usdt-logo.svg" alt="USDT" class="coin-icon">
              <span>USDT</span>
            </div>
            <div class="crypto-card" :class="{'iscrypto-card':cenryindex == 'BTC' }" @click="TaBa('BTC')">
              <img src="https://cryptologos.cc/logos/tether-usdt-logo.svg" alt="BTC" class="coin-icon">
              <span>BTC</span>
            </div>
            <div class="crypto-card" :class="{'iscrypto-card':cenryindex == 'ETH' }" @click="TaBa('ETH')">
              <img src="https://cryptologos.cc/logos/tether-usdt-logo.svg" alt="ETH" class="coin-icon">
              <span>ETH</span>
            </div>
          </div>

          <!-- 网络 -->
          <div class="form-item">
            <div class="label">{{ $t('网络') }}</div>
            <div class="network-list">
              <div
                v-for="network in networks"
                :key="network"
                :class="['network-item', { active: form.network === network }]"
                @click="handleSelectNetwork(network)"
              >
                {{ network }}
              </div>
            </div>
          </div>

          <!-- 地址 -->
          <div class="form-item">
            <div class="label">{{ $t('地址') }}</div>
            <el-input
              v-model="form.address"
              :placeholder="$t('请输入钱包地址')"
              :maxlength="100"
            >
              <template #append>
                <el-button @click="handlePaste">
                  <i class="far fa-clipboard"></i>
                </el-button>
              </template>
            </el-input>
          </div>

          <!-- 备注 -->
          <div class="form-item">
            <div class="label">{{ $t('备注') }}</div>
            <el-input
              v-model="form.remark"
              :placeholder="$t('请输入备注信息（选填）')"
              :maxlength="20"
              show-word-limit
            />
          </div>

          <!-- 默认地址设置 -->
          <div class="form-item no-label">
            <el-checkbox v-model="form.isDefault">
              {{ $t('设为默认地址') }}
              <el-tooltip :content="$t('默认地址将在提款时优先显示')">
                <i class="fas fa-question-circle help-icon"></i>
              </el-tooltip>
            </el-checkbox>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">{{ $t('取消') }}</el-button>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleSubmit"
          >
            {{ $t('确认添加') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </template>

  <script lang="ts">
  import { defineComponent } from 'vue'

  export default defineComponent({
    name: 'AddWalletDialog'
  })
  </script>

  <script setup lang="ts">
  import { ref, computed } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { AddressForm } from '@/views/assets/types'

  interface Props {
    modelValue: boolean
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 简化网络列表
  const networks = ref(['TRC20', 'ERC20', 'BEP20'])
  
  const cenryindex = ref('USDT')
  
  const TaBa = (index): void => {
    console.log(index,'TaBa');
    cenryindex.value = index;
    if(index == 'USDT'){
      networks.value = ['TRC20', 'ERC20', 'BEP20']
    }
    if(index == 'BTC'){
      networks.value = ['TRC20', 'ERC20']
    }
    if(index == 'ETH'){
      networks.value = ['ERC20']
    }
  }
  // 状态变量
  const loading = ref(false)

  // 表单数据
  const form = ref<AddressForm>({
    crypto: cenryindex.value,  // 默认选中 USDT
    network: '',
    address: '',
    remark: '',
    isDefault: false
  })

  // 计算属性
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  // 检测是否为移动端
  const isMobile = ref(window.innerWidth <= 768)

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    isMobile.value = window.innerWidth <= 768
  })

  // 方法
  const handleSubmit = async (): Promise<void> => {
    let obj = {
      coinName:cenryindex.value,
      walletInternet:form.value.network,
      walletAddress:form.value.address,
      remark:form.value.remark,
      isDefault:form.value.isDefault?1:0,
    }
    try {
      if (!form.value.network) {
        ElMessage.warning('请选择网络')
        return
      }

      // if (!validateAddress(form.value.address)) {
      //   ElMessage.warning('请输入正确格式的钱包地址')
      //   return
      // }

      loading.value = true
      await new Promise(resolve => setTimeout(resolve, 1000))
      // ElMessage.success('添加成功')
      emit('success',obj);
      handleCancel()
    } catch (error) {
      console.error('添加失败:', error)
    } finally {
      loading.value = false
    }
  }

  const handleCancel = (): void => {
    visible.value = false
    resetForm()
  }

  const resetForm = (): void => {
    form.value = {
      crypto: cenryindex.value,
      network: '',
      address: '',
      remark: '',
      isDefault: false
    }
  }

  // 修改选择网络方法
  const handleSelectNetwork = (network: string) => {
    form.value.network = network
  }

  // 添加地址验证方法
  const validateAddress = (value: string): boolean => {
    if (!value) return false
    if (value.length < 30) return false

    // 根据不同网络验证地址格式
    if (form.value.network === 'TRC20' && !value.startsWith('T')) return false
    if ((form.value.network === 'ERC20' || form.value.network === 'BEP20') &&
        !value.startsWith('0x')) return false

    return true
  }

  // 修改粘贴方法，添加验证
  const handlePaste = async (): Promise<void> => {
    try {
      const text = await navigator.clipboard.readText()
      const address = text.trim()
      // if (!validateAddress(address)) {
      //   ElMessage.warning('无效的钱包地址格式')
      //   return
      // }
      form.value.address = address
    } catch (error) {
      ElMessage.warning('无法访问剪贴板')
    }
  }
  </script>

  <style lang="scss" scoped>
  .wallet-dialog {
    :deep(.el-dialog__header) {
      padding: 20px 24px;
      margin: 0;
      border-bottom: 1px solid #eee;

      .el-dialog__title {
        font-size: 16px;
        font-weight: 500;
      }
    }

    :deep(.el-dialog__body) {
      padding: 0;
    }

    @media (max-width: 768px) {
      :deep(.el-dialog__header) {
        padding: 16px;
      }

      .dialog-content {
        padding: 16px;
      }

      .dialog-footer {
        padding: 12px 16px;
      }

      .network-list {
        grid-template-columns: repeat(2, 1fr);
      }
    }
  }

  .dialog-content {
    padding: 20px 24px;
  }

  .security-tip {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    padding: 12px 16px;
    background: #fff9e6;
    border-radius: 4px;
    margin-bottom: 24px;

    i {
      color: #e47911;
      font-size: 16px;
      margin-top: 2px;
    }

    span {
      color: #333;
      font-size: 14px;
      line-height: 1.5;
    }
  }

  .form-content {
    .form-item {
      margin-bottom: 20px;

      &:last-child {
        margin-bottom: 0;
      }

      &.no-label {
        padding-left: 80px;
      }

      .label {
        font-size: 14px;
        color: #606266;
        margin-bottom: 8px;
      }
    }
  }

  .crypto-card {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    background: #f8f8f8;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-right: 5px;
    margin-bottom: 5px;

    .coin-icon {
      width: 20px;
      height: 20px;
    }

    span {
      font-size: 14px;
      color: #333;
    }
  }
  .iscrypto-card{
    color: #409eff;
    border-color: #409eff;
    background: #ecf5ff;
  }
  .network-list {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    .network-item {
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid #ddd;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      color: #666;
      background: #f8f8f8;
      user-select: none;
      transition: background-color 0.2s;

      &:hover {
        color: #333;
        border-color: #c0c4cc;
      }

      &.active {
        color: #409eff;
        border-color: #409eff;
        background: #ecf5ff;
      }
    }
  }

  .help-icon {
    color: #909399;
    font-size: 14px;
    margin-left: 4px;
  }

  .dialog-footer {
    padding: 16px 24px;
    background: #f8f8f8;
    border-top: 1px solid #eee;
    text-align: right;
  }
  </style>
